<?php
/**
 * Created by PhpStorm.
 * User: xuanbang.wen
 * Date: 2020/2/18
 * Time: 9:58
 */

namespace App\Web\Controller;


use App\Facades\UrlCrypt;
use App\Web\Facades\UserAuth;
use App\Web\Model\RabbitMQ\NoticeProducer;
use EchoPHP\Http\Request;
use App\Web\Model\VideoInterview as VideoInterviewModel;
use EchoPHP\Validator\Validator;
use App\Web\Service\RightCheck;
use App\Api\Model\Interview;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;


class VideoInterview extends Controller {

    public $rightCheck = [
        'createRoomCheck' => RightCheck::RIGHT_VIDEOINTERVIEW_ALL,
        'jobseekerCheck' => RightCheck::RIGHT_VIDEOINTERVIEW_ALL,
        'teamRoomList' => RightCheck::RIGHT_VIDEOINTERVIEW_ALL,
        'teamRoomDetail' => RightCheck::RIGHT_VIDEOINTERVIEW_ALL,
    ];

    /**
     * Notes:创建房间申请
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Throwable
     */
    public function createRoomApply(Request $request) {
        $roomInfo = [
            'roomname' => $request->getParam('roomname'),
            'starttime' => $request->getParam('starttime'),
            'endtime' => $request->getParam('endtime'),
            'projectid' => $request->getParam('projectid'),
            'linktype' => 4,
            'interviewerids' => $request->getParam('interviewerids'),
            'istemp' => $request->getParam('istemp', 0),
        ];
        $rule = [
            'roomname|房间名称' => [
                'required'
            ],
            'starttime|开始面试时间' => [
                'required', 'dateFormat' => 'Y-m-d H:i:s'
            ],
            'endtime|结束面试时间' => [
                'required'
            ],
            'projectid|项目id' => [
                'required'
            ],
            'interviewerids|面试官id' => [
                'required'
            ],
            'istemp|是否为正式面试' => [
                'required'
            ],
        ];
        $validate = new Validator($rule);
        if (!$validate->validate($roomInfo)) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => $validate->getErrors()
            ]);
        }
        if ($roomInfo['starttime'] < date('Y-m-d H:i:s')) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => ['starttime' => '开始时间不能小于现在时间'],
            ]);
        }
        if (date('Y-m-d', strtotime($roomInfo['endtime'])) != date('Y-m-d', strtotime($roomInfo['starttime']))) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => ['endtime' => '结束时间与开始时间应为同一天'],
            ]);
        }
        if ($roomInfo['endtime'] < $roomInfo['starttime']) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => ['endtime' => '结束时间不能小于开始时间'],
            ]);
        }
        $model = new VideoInterviewModel();
        $roomId = $model->createRoomApply($roomInfo);
        if ($roomId > 0){
            $user = UserAuth::getLoginInfo();
            //消息通知
            $noticeProducer = new NoticeProducer();
            $noticeProducer->add(NoticeProducer::MODULE_INTERVIEW_APPLY, [
                'roomid' => $roomId,
                'userid' => $user['userid'],
                'handlerid' => $user['userid'],
                'handlername' => $user['cname'],
                'description' => '申请视频面试房间',
            ], false);
        }
        return $this->json([
            'status' => $roomId > 0,
            'message' => $roomId > 0 ? '已添加，待审批人员审批' : '创建失败',
            'roomid' => $roomId
        ]);
    }

    /**
     * Notes:创建房间审核
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Throwable
     */
    public function createRoomCheck(Request $request) {
        $roomId = $request->getParam('roomid');
        $status = $request->getParam('status');
        $reason = $request->getParam('reason');
        $result = (new VideoInterviewModel())->createRoomCheck($roomId, $status, $reason);
        return $this->json($result);
    }

    /**
     * Notes:添加求职者
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function addJobseeker(Request $request) {
        $roomId = $request->getParam('roomid');
        $jobseekerInfo = $request->getParam('jobseekers');
        $jobseekerInfo = json_decode($jobseekerInfo, true);
        $result = (new VideoInterviewModel())->addJobseeker($roomId, $jobseekerInfo);
        return $this->json($result);
    }

    /**
     * Notes:修改求职者面试安排时间
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function updateJobseekerTime(Request $request) {
        $jobseekers = $request->getParam('jobseekers');
        $roomId = $request->getParam('roomid');
        $result = (new VideoInterviewModel())->updateJobseekerTime($jobseekers, $roomId);
        return $this->json($result);
    }

    /**
     * Notes:添加面试官
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function addInterviewer(Request $request) {
        $roomId = $request->getParam('roomid');
        $interviewIds = $request->getParam('interviewerids');
        $result = (new VideoInterviewModel())->addInterviewer($roomId, $interviewIds);
        return $this->json($result);
    }

    /**
     * Notes:团队房间列表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function teamRoomList(Request $request) {
        $pageNum = $request->getParam('pagenum/d', 1);
        $pageLimit = $request->getParam('pagelimit/d', 10);
        $params = [
            'roomname' => $request->getParam('roomname', ''),
            'status' => $request->getParam('status', '01'),
            'startdate' => $request->getParam('startdate'),
            'crmprojectnum' => $request->getParam('crmprojectnum'),
            'projectname' => $request->getParam('projectname', ''),
        ];
        $model = new VideoInterviewModel();
        $user = UserAuth::getLoginInfo();
        if ($user['issuper'] != 1) {
            $params['teamcode'] = $user['teamcode'];
        }
        list($pageNum, $rowFrom, $rowTo) = $model->paginationParameters($pageNum, $pageLimit);
        $count = $model->teamRoomListCount($params);
        $roomList = [];
        if ($count) {
            $roomList = $model->teamRoomList($params, $rowFrom, $rowTo);
        }
        return $this->json([
            'status' => true,
            'message' => '获取成功',
            'roomlist' => $roomList,
            'totalcount' => intval($count),
            'pagenum' => $pageNum,
        ]);
    }

    /**
     * Notes:我的可用房间列表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function myUsableRoomList(Request $request) {
        $pageNum = $request->getParam('pagenum/d', 1);
        $pageLimit = 10;
        $model = new VideoInterviewModel();
        list($pageNum, $rowFrom, $rowTo) = $model->paginationParameters($pageNum, $pageLimit);
        $params = [
            'roomname' => $request->getParam('roomname', ''),
            'projectid' => $request->getParam('projectid', ''),
            'startdate' => $request->getParam('startdate'),
        ];

        $hasRight = $model->chkInterviewerRight($params['projectid']);
        if (!$hasRight) {
            return $this->json([
                'status' => false,
                'message' => '无权限',
                'roomlist' => [],
                'totalcount' => 0,
                'pagenum' => 1,
            ]);
        }

        $roomList = [];
        $count = $model->myUsableRoomCount($params);
        if ($count) {
            $roomList = $model->myUsableRoomList($params, $rowFrom, $rowTo);
        }
        return $this->json([
            'status' => true,
            'message' => '获取成功',
            'roomlist' => $roomList,
            'totalcount' => intval($count),
            'pagenum' => $pageNum,
        ]);
    }

    /**
     * Notes:我的房间列表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function myRoomList(Request $request) {
        $pageNum = $request->getParam('pagenum/d', 1);
        $pageLimit = $request->getParam('pagelimit/d', 10);
        $params = [
            'roomname' => $request->getParam('roomname', ''),
            'projectid' => $request->getParam('projectid', ''),
            'projectname' => $request->getParam('projectname', ''),
            'crmprojectnum' => $request->getParam('crmprojectnum'),
            'startdate' => $request->getParam('startdate'),
        ];
        $model = new VideoInterviewModel();
        list($pageNum, $rowFrom, $rowTo) = $model->paginationParameters($pageNum, $pageLimit);
        $count = $model->myRoomListCount($params);
        $roomList = [];
        if ($count) {
            $roomList = $model->myRoomList($params, $rowFrom, $rowTo);
        }
        return $this->json([
            'status' => true,
            'message' => '获取成功',
            'roomlist' => $roomList,
            'totalcount' => intval($count),
            'pagenum' => $pageNum,
        ]);
    }

    /**
     * Notes:我的房间信息明细
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function myRoomDetail(Request $request) {
        $roomId = $request->getParam('roomid');
        $roomDetail = (new VideoInterviewModel())->myRoomDetail($roomId);
        return $this->json([
            'status' => true,
            'message' => '查询成功',
            'roominfo' => $roomDetail['roominfo'],
            'interviewers' => $roomDetail['interviewers'],
            'jobseekers' => $roomDetail['jobseekers'],
        ]);
    }

    /**
     * Notes:团队房间信息明细
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function teamRoomDetail(Request $request) {
        $roomId = $request->getParam('roomid');
        $roomDetail = (new VideoInterviewModel())->teamRoomDetail($roomId);
        return $this->json([
            'status' => true,
            'message' => '查询成功',
            'roominfo' => $roomDetail['roominfo'],
            'interviewers' => $roomDetail['interviewers'],
            'jobseekers' => $roomDetail['jobseekers'],
        ]);
    }

    /**
     * Notes:房间删除求职者
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function delJobseeker(Request $request) {
        $jobseekerId = $request->getParam('jobseekerid', 0);
        $roomId = $request->getParam('roomid', 0);
        $result = (new VideoInterviewModel())->delJobseeker($roomId, $jobseekerId);
        return $this->json($result);
    }

    /**
     * Notes:删除面试官
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function delInterviewer(Request $request) {
        $roomInterviewerId = $request->getParam('interviewerid', 0);
        $roomId = $request->getParam('roomid', 0);
        $result = (new VideoInterviewModel())->delInterview($roomId, $roomInterviewerId);
        return $this->json($result);
    }

    /**
     * Notes:顾问取消面试房间
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function cancelRoom(Request $request) {
        $roomId = $request->getParam('roomid', 0);
        $result = (new VideoInterviewModel())->cancelRoom($roomId);
        return $this->json($result);
    }

    /**
     * Notes:简历面试记录
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function resumeInterviewRecords(Request $request) {
        return $this->json([
            'status' => true,
            'message' => '获取成功',
            'records' => [],
        ]);

        $resumeId = $request->getParam('resumeids', []);
        $model = new VideoInterviewModel();
        $records = $model->resumeInterviewRecords($resumeId);
        return $this->json([
            'status' => true,
            'message' => '获取成功',
            'records' => $records,
        ]);
    }

    /**
     * Notes:发送求职者提醒
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function remindJobseeker(Request $request) {
        $vs_jobseekerIds = $request->getParam('jobseekerid_outs', []);
        if (!$vs_jobseekerIds) {
            return $this->json([
                'status' => false,
                'message' => '发送失败',
            ]);
        }
        $model = new VideoInterviewModel();
        $myJobseekers = $model->myJobseekers($vs_jobseekerIds);
        if (!$myJobseekers) {
            return $this->json([
                'status' => false,
                'message' => '发送失败',
            ]);
        }
        $interviewApi = new Interview();
        $rightFlag = [];
        foreach ($myJobseekers as $jobseekerId) {
            if (!isset($rightFlag[$jobseekerId['projectid']])) {
                $result = $model->chkInterviewerRight($jobseekerId['projectid']);
                $rightFlag[$jobseekerId['projectid']] = $result;
                if (!$result) {
                    return $this->json([
                        'status' => false,
                        'message' => '无权限',
                    ]);
                }
            }
        }
        foreach ($myJobseekers as $jobseekerId) {
            $interviewApi->remindJobseeker($jobseekerId['jobseekerid_out'], 1);
        }
        return $this->json([
            'status' => true,
            'message' => '已发送通知',
        ]);
    }

    /**
     * Notes:发送面试官提醒
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function remindInterviewer(Request $request) {
        $vs_interviewIds = $request->getParam('interviewerid_out', []);
        if (!$vs_interviewIds) {
            return $this->json([
                'status' => false,
                'message' => '发送失败',
            ]);
        }
        $model = new VideoInterviewModel();
        $myInterviewers = $model->myInterviewer($vs_interviewIds);
        if (!$myInterviewers) {
            return $this->json([
                'status' => false,
                'message' => '发送失败',
            ]);
        }
        //$myInterviewers = array_column($myInterviewers, 'interviewerid_out');
        $interviewApi = new Interview();
        $rightFlag = [];
        foreach ($myInterviewers as $interviewId) {
            if (!isset($rightFlag[$interviewId['projectid']])) {
                $result = $model->chkInterviewerRight($interviewId['projectid']);
                $rightFlag[$interviewId['projectid']] = $result;
                if (!$result) {
                    return $this->json([
                        'status' => false,
                        'message' => '无权限',
                    ]);
                }
            }
        }
        foreach ($myInterviewers as $interviewId) {
            $interviewApi->remindInterviewer($interviewId['interviewerid_out'], 1);
        }
        return $this->json([
            'status' => true,
            'message' => '已发送通知',
        ]);
    }

    /**
     * Notes:面试结果
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function interviewResult(Request $request) {
        $roomId = $request->getParam('roomid', 0);
        $jobseekerId = $request->getParam('jobseekerid', 0);
        $model = new VideoInterviewModel();
        $result = $model->interviewResult($roomId, $jobseekerId);
        return $this->json($result);
    }

    /**
     * Notes:面试详情导出
     * @param Request $request
     * @return \EchoPHP\Http\Response\StreamedResponse | \EchoPHP\Http\Response\JsonResponse
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function export(Request $request) {
        $roomId = $request->getParam('roomid', 0);
        return (new VideoInterviewModel())->export($roomId);
    }

    /**
     * Notes:检查面试是否冲突
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function checkInterivewer(Request $request) {
        $interviewIds = $request->getParam('interviewids', 0);
        $starttime = $request->getParam('starttime', 0);
        $endtime = $request->getParam('endtime', 0);
        $result = (new VideoInterviewModel())->checkInterviewers($starttime, $endtime, $interviewIds);
        if ($result) {
            $message = '面试官安排有冲突： <br>';
            foreach ($result as $item) {
                $message .= $item['cname'] . '－' . $item['mobilephone'] . '，在' . date('H:i', strtotime($item['starttime'])) . '-' . date('H:i', strtotime($item['endtime'])) . '有面试安排' . '<br>';
            }
            return $this->json([
                'status' => false,
                'message' => $message,
            ]);
        }
        return $this->json([
            'status' => true,
            'message' => '无冲突',
        ]);
    }

    /**
     * Notes:获取求职者面试录像
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function jobseekerVideo(Request $request) {
        $jobseekerId = $request->getParam('jobseekerid', 0);
        $model = new VideoInterviewModel();
        $result = $model->jobseekerVideo($jobseekerId);
        $clientUrl = config('extraapi.vsapi.rpoclient_url', '');

        foreach ($result as &$item) {
            $token = UrlCrypt::generateToken(['id' => $item['uuid']], 604800);
            $item['videopath'] = $clientUrl . 'video?type=1&id=' . $item['uuid'] . '&token=' . $token;
        }
        $videoPath = $clientUrl . 'video?type=2&id=' . $jobseekerId . '&token=' . UrlCrypt::generateToken(['id' => $jobseekerId], 604800);
        return $this->json([
            'status' => true,
            'message' => '获取成功',
            'videolist' => $result,
            'videopath' => $videoPath,
        ]);
    }
}
